package com.showsu.editor.interceptor;

import com.alibaba.fastjson.JSON;
import com.showsu.editor.common.StatusCode;
import com.showsu.editor.config.SpringContextUtil;
import com.showsu.editor.session.ISession;
import com.showsu.editor.session.redis.RedisSessionManager;
import com.showsu.editor.utils.BsResult;
import com.showsu.editor.utils.OsAndBrowserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: William
 * @Description: 会话拦截器
 * @Date: Created in 2:26 下午 2024/9/13
 * @Modified By:
 */
@Slf4j
@DependsOn("userSessionManager")
public class UserSessionInterceptor implements HandlerInterceptor {

    private static final String LOGIN_NOT = "未登录，请先登录";
    private static final String LOGIN_VALID = "登录已过期，请重新登录";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RedisSessionManager userSessionManager = SpringContextUtil.getBean(RedisSessionManager.class);
        ISession session = userSessionManager.getSession(request);
        if (session != null && session.getUserId() != null) {
            return true;
        }
        Map<String, Object> map= new HashMap<>(8);
        if ("/api/user/info".equals(request.getServletPath())) {
            //用户信息接口在未登录状态下不报异常码，确保前端首页正常展示
            map.put("code", StatusCode.SUCCESS);
            map.put("msg", BsResult.successMsg);
        } else {
            map.put("code", StatusCode.NOT_LOGIN);
            map.put("msg", session == null ? LOGIN_NOT : LOGIN_VALID);
            OsAndBrowserUtil osAndBrowserUtil = OsAndBrowserUtil.getOSAndBrowser((HttpServletRequest) request);
            log.error("未登录！,IP:{},os:{},browser:{}",  osAndBrowserUtil.getIP(), osAndBrowserUtil.getOs(),osAndBrowserUtil.getBrowser());
        }
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(map));
        writer.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
